package cn.prophet.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Time;
import java.util.*;

import cn.prophet.bean.*;
import cn.prophet.constant.BjksWithValueBean;
import cn.prophet.mapper.*;
import cn.prophet.service.AccountDetailedService;
import cn.prophet.service.ForeignService;
import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import cn.prophet.service.BjKRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;

@Service
@Slf4j
public class BjKRecordServiceImpl implements BjKRecordService {
    @Resource
    private BjksRecordMapper bjksRecordMapper;
    @Resource
    private GameOrderMapper gameOrderMapper;
    @Resource
    private UserMapper userMapper;

    @Resource
    private ForeignService foreignService;

    @Resource
    private AccountDetailedService accountDetailedService;

    @Value("${game.award.percentage}")
    private double awardPercentage;

    @Resource
    private OpenAccountMapper openAccountMapper;

    @Resource
    private AccountDetailedMapper accountDetailedMapper;

    @Override
    public int addRecord(String num, Date date, byte recordType,byte gameCategory) {
        BjksRecord record = new BjksRecord();
        record.setNum(String.valueOf(num));
        record.setCreateTime(date);
        record.setGameCategory(gameCategory);
        long end = date.getTime() + 10 * 60 * 1000;
        record.setEndTime(new Date(end));
        record.setRecordType(recordType);

        return bjksRecordMapper.insertSelective(record);
    }

    @Override
    public List<BjksRecord> getBjksRecord(Byte gameCategory) {

        List<BjksRecord> recordResult = bjksRecordMapper.selectCurrentDay(gameCategory);

        return recordResult;
    }

    @Override
    public void getBjGovList() {
        List<BjksRecord> list = bjksRecordMapper.getRecordLessDate((byte) 1,new Date());
        if (list == null) {
            return;
        }
        BjksRecord govRecord = null;
        Document document;
        try {
            document = Jsoup.connect("https://m.pub.icaile.com/bjk3/").userAgent(
                    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36")
                    .referrer("https://m.pub.icaile.com/bjk3/").get();

            Elements els = document.getElementById("firstTbody").getElementsByTag("tr");
            Element lastEl =null;
            for (int i = 0;i<els.size();i++){
                String classAttr = els.get(i).attr("class");

                if("hidetr".equals(classAttr)){
                    break;
                }
                lastEl = els.get(i);
            }
            //190115-063
            Elements elss = lastEl.getElementsByTag("td");
            String numStr = elss.get(0).text();
            String [] mArray = numStr.split("-0");
            StringBuffer openCode = new StringBuffer();
            Elements ems = lastEl.getElementsByClass("lottery_box").first().getElementsByTag("em");

            govRecord = new BjksRecord();
            govRecord.setNum("20"+mArray[0]+mArray[1]);
            govRecord.setOpencode(ems.get(0).text()+","+ems.get(1).text()+","+ems.get(2).text());

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.info("拉数据异常:" + e.getMessage());
        }
        if (govRecord != null) {
            // 添加开奖记录到数据库
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    String sqlnum = list.get(i).getNum();
                    if (list.get(i).getOpencode()==null&&sqlnum.equals(govRecord.getNum())) {
                        BjksRecord insertRecord = list.get(i);
                        insertRecord.setOpencode(govRecord.getOpencode());
                        insertRecord.setOpenLotteryTime(new Time(System.currentTimeMillis()));
                        bjksRecordMapper.updateByPrimaryKey(insertRecord);
                        dealGameResult(govRecord.getOpencode(), govRecord.getNum(), (byte) 1);
                    }

                }
            }

        }
    }

    /**
     *  宁夏快三
     */
    @Override
    public void getNxGovList() {

        List<BjksRecord> list = bjksRecordMapper.getRecordLessDate((byte) 3,new Date());

        if (list == null) {
            return;
        }

        Map<String,String> map = foreignService.getNxOpenCode();

        if(map!=null){
            BjksRecord govRecord = new BjksRecord();
            govRecord.setNum(map.get("num"));
            govRecord.setOpencode(map.get("openCode"));
            // 添加开奖记录到数据库
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    String sqlnum = list.get(i).getNum();
                    if (list.get(i).getOpencode()==null&&sqlnum.equals(govRecord.getNum())) {
                        BjksRecord insertRecord = list.get(i);
                        insertRecord.setOpencode(govRecord.getOpencode());
                        insertRecord.setOpenLotteryTime(new Time(System.currentTimeMillis()));
                        bjksRecordMapper.updateByPrimaryKey(insertRecord);
                        dealGameResult(govRecord.getOpencode(), govRecord.getNum(), (byte) 3);
                    }

                }
            }

        }else{

        }



    }

    @Override
    public void getJsGovList() {

        List<BjksRecord> list = bjksRecordMapper.getRecordLessDate((byte) 2,new Date());
        if (list == null) {
            return;
        }

        Map<String,String> map = foreignService.getJsOpenCode();

        if(map!=null){
            BjksRecord govRecord = new BjksRecord();
            govRecord.setNum(map.get("num"));
            govRecord.setOpencode(map.get("openCode"));
            // 添加开奖记录到数据库
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    String sqlnum = list.get(i).getNum();
                    if (list.get(i).getOpencode()==null&&sqlnum.equals(govRecord.getNum())) {
                        BjksRecord insertRecord = list.get(i);
                        insertRecord.setOpencode(govRecord.getOpencode());
                        insertRecord.setOpenLotteryTime(new Time(System.currentTimeMillis()));
                        bjksRecordMapper.updateByPrimaryKey(insertRecord);
                        dealGameResult(govRecord.getOpencode(), govRecord.getNum(), (byte) 2);
                    }

                }
            }

        }else{

        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int bettingGame(Byte gameCategory, Long userId, Byte gameType, String gameResult, String recordId, Byte buyNum, Short multiple, BigDecimal singleAmount, BigDecimal bettingAmount, BigDecimal winningAmount) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return 5;
        } else {
            BigDecimal balance = user.getBalance();
            if (balance.doubleValue() < bettingAmount.doubleValue()) {
                //余额不足
                return 4;
            }
        }
        //验证gameResult 值
        List<String> results = JSON.parseArray(gameResult, String.class);
        if (results == null || results.size() == 0) {
            return 3;
        }
        BjksRecordExample bjksRecordExample = new BjksRecordExample();
        BjksRecordExample.Criteria criteria = bjksRecordExample.createCriteria();
        criteria.andNumEqualTo(recordId);
        List<BjksRecord> recordList = bjksRecordMapper.selectByExample(bjksRecordExample);
        if (recordList == null) {
            return 0;
        }
        if (recordList.size() != 1) {
            return 0;
        }
        Date endTime = recordList.get(0).getEndTime();
        Long end = endTime.getTime();
        Long current = System.currentTimeMillis();
        if ((end - current) < 4 * 60 * 1000) {
            //本期号码不再押注时间内
            return 2;
        }
        User currentUser = new User();
        currentUser.setUserId(userId);
        currentUser.setBalance(user.getBalance().subtract(bettingAmount));
        userMapper.updateByPrimaryKeySelective(currentUser);

        //收支明细
        accountDetailedService.updateAccount((byte) 1,bettingAmount,"下注",userId);

        GameOrder gameOrder = new GameOrder();
        gameOrder.setGameCategory(gameCategory);
        gameOrder.setUserId(userId);
        gameOrder.setGameType(gameType);
        gameOrder.setGameResult(gameResult);
        gameOrder.setRecordId(recordId);
        gameOrder.setBuyNum(buyNum);
        gameOrder.setMultiple(multiple);
        gameOrder.setSingleAmount(singleAmount);
        gameOrder.setBettingAmount(bettingAmount);
        gameOrder.setWinningAmount(winningAmount);
        gameOrder.setCreateTime(new Date());
        return gameOrderMapper.insertSelective(gameOrder);
    }

    /**
     *
     * @param userId
     * @param showType 1 展示未开奖的 2展示已开奖的
     * @return
     */
    @Override
    public List<GameOrder> getGameOrder(Long userId,Byte showType,Byte game_category) {
        BjksRecord record = bjksRecordMapper.selectCurrentRecord(game_category);
        GameOrderExample gameOrderExample = new GameOrderExample();
        GameOrderExample.Criteria criteria = gameOrderExample.createCriteria();
        if(showType==1){
            if(record==null){
                return null;
            }else{
                criteria.andUserIdEqualTo(userId);
                criteria.andGameCategoryEqualTo(game_category);
                criteria.andRecordIdGreaterThanOrEqualTo(record.getNum());
                criteria.andDealStatusEqualTo((byte) 0);
                gameOrderExample.setOrderByClause("create_time desc");
                return gameOrderMapper.selectByExample(gameOrderExample);
            }

        }else if(showType==2){
            criteria.andUserIdEqualTo(userId);
            criteria.andGameCategoryEqualTo(game_category);
            if(record!=null){
                criteria.andRecordIdLessThan(record.getNum());
            }
            gameOrderExample.setOrderByClause("create_time desc");
            return gameOrderMapper.selectByExample(gameOrderExample);
        }

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealGameResult(String openCode, String num,byte gameGategory) {
        GameOrderExample gameOrderExample = new GameOrderExample();
        GameOrderExample.Criteria criteria = gameOrderExample.createCriteria();
        criteria.andRecordIdEqualTo(num);
        criteria.andGameCategoryEqualTo(gameGategory);
        List<GameOrder> orderList = gameOrderMapper.selectByExample(gameOrderExample);
        String[] codeNum = openCode.split(",");
        if (codeNum.length != 3) {
            return;
        }
        if (orderList != null && orderList.size() > 0) {
            for (int i = 0; i < orderList.size(); i++) {
                byte gameType = orderList.get(i).getGameType();
                byte dealStatus = orderList.get(i).getDealStatus();
                switch (gameType) {
                    case 1:
                        //和值

                        if (dealStatus == 0) {
                            String gameResult = orderList.get(i).getGameResult();
                            List<BjksWithValueBean> list = JSON.parseArray(gameResult, BjksWithValueBean.class);
                            if (list != null && list.size() > 0) {
                                boolean lottery = false;
                                for (int j = 0; j < list.size(); j++) {
                                    int withValue = Integer.parseInt(list.get(j).getWithValue());
                                    int serverValue = Integer.parseInt(codeNum[0]) + Integer.parseInt(codeNum[1]) + Integer.parseInt(codeNum[2]);
                                    if (withValue == serverValue) {
                                        //中奖了
                                        lottery = true;
                                        GameOrder gameOrder = new GameOrder();
                                        gameOrder.setId(orderList.get(i).getId());
                                        gameOrder.setDealStatus((byte) 1);
                                        gameOrder.setWinRecord("和值("+serverValue+")");
                                        gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                        BigDecimal myBalance;
                                        if (orderList.get(i).getSingleAmount().doubleValue() == 2.00) {
                                            User user = new User();
                                            user.setUserId(orderList.get(i).getUserId());
                                            myBalance = list.get(j).getWinning_amount().multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                            user.setBalance(myBalance);
                                            userMapper.addBalanceByPrimaryKey(user);
                                        } else {
                                            User user = new User();
                                            user.setUserId(orderList.get(i).getUserId());
                                            myBalance = list.get(j).getWinning_amount().multiply(new BigDecimal(0.1)).multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                            user.setBalance(myBalance);
                                            userMapper.addBalanceByPrimaryKey(user);
                                        }

                                        gameAwardDeql(orderList.get(i).getUserId(),myBalance);
                                        accountDetailedService.updateAccount((byte) 2,myBalance,"中奖",orderList.get(i).getUserId());
                                        //追号
                                        refundChase(orderList.get(i));


                                        break;
                                    }
                                }
                                if (!lottery) {
                                    //没中奖
                                    GameOrder gameOrder = new GameOrder();
                                    gameOrder.setId(orderList.get(i).getId());
                                    gameOrder.setDealStatus((byte) 2);
                                    gameOrderMapper.updateByPrimaryKeySelective(gameOrder);

                                }
                            }
                        }
                        break;
                    case 2:
                        //三同号单选
                        if (dealStatus == 0) {
                            int value1 = Integer.parseInt(codeNum[0]);
                            int value2 = Integer.parseInt(codeNum[1]);
                            int value3 = Integer.parseInt(codeNum[2]);
                            if (value1 == value2 && value2 == value3) {
                                String gameResult = orderList.get(i).getGameResult();
                                List<String> list = JSON.parseArray(gameResult, String.class);
                                if (list != null && list.size() > 0) {
                                    boolean lottery = false;
                                    for (int j = 0; j < list.size(); j++) {
                                        String results = list.get(j);
                                        String[] resultArray = results.split(",");
                                        if (resultArray != null && resultArray.length == 3) {
                                            int result1 = Integer.parseInt(resultArray[0]);
                                            int result2 = Integer.parseInt(resultArray[1]);
                                            int result3 = Integer.parseInt(resultArray[2]);
                                            if (result1 == result2 && result2 == result3 && value1 == result1) {
                                                lottery = true;
                                                //中奖了
                                                GameOrder gameOrder = new GameOrder();
                                                gameOrder.setId(orderList.get(i).getId());
                                                gameOrder.setDealStatus((byte) 1);
                                                gameOrder.setWinRecord("三同号单选("+results+")");
                                                gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                                BigDecimal myBalance;
                                                if (orderList.get(i).getSingleAmount().doubleValue() == 2.00) {
                                                    User user = new User();
                                                    user.setUserId(orderList.get(i).getUserId());
                                                    myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                    user.setBalance(myBalance);
                                                    userMapper.addBalanceByPrimaryKey(user);
                                                } else {
                                                    User user = new User();
                                                    user.setUserId(orderList.get(i).getUserId());
                                                    myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(0.1)).multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                    user.setBalance(myBalance);
                                                    userMapper.addBalanceByPrimaryKey(user);
                                                }
                                                gameAwardDeql(orderList.get(i).getUserId(),myBalance);
                                                accountDetailedService.updateAccount((byte) 2,myBalance,"中奖",orderList.get(i).getUserId());

                                                //追号
                                                refundChase(orderList.get(i));
                                                break;
                                            }
                                        }

                                    }
                                    if (!lottery) {
                                        //未中奖
                                        GameOrder gameOrder = new GameOrder();
                                        gameOrder.setId(orderList.get(i).getId());
                                        gameOrder.setDealStatus((byte) 2);
                                        gameOrderMapper.updateByPrimaryKeySelective(gameOrder);

                                    }
                                }
                            } else {
                                //未中奖
                                GameOrder gameOrder = new GameOrder();
                                gameOrder.setId(orderList.get(i).getId());
                                gameOrder.setDealStatus((byte) 2);
                                gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                            }

                        }
                        break;
                    case 3:
                        //三同号通选
                        if (dealStatus == 0) {
                            int value1 = Integer.parseInt(codeNum[0]);
                            int value2 = Integer.parseInt(codeNum[1]);
                            int value3 = Integer.parseInt(codeNum[2]);
                            if (value1 == value2 && value2 == value3) {
                                String gameResult = orderList.get(i).getGameResult();
                                List<String> list = JSON.parseArray(gameResult, String.class);
                                if (list != null && list.size() > 0) {
                                    boolean lottery = false;
                                    for (int j = 0; j < list.size(); j++) {
                                        String results = list.get(j);
                                        String[] resultArray = results.split(",");
                                        if (resultArray != null && resultArray.length == 3) {
                                            int result1 = Integer.parseInt(resultArray[0]);
                                            int result2 = Integer.parseInt(resultArray[1]);
                                            int result3 = Integer.parseInt(resultArray[2]);
                                            if (result1 == result2 && result2 == result3 && value1 == result1) {
                                                //中奖了
                                                lottery = true;
                                                GameOrder gameOrder = new GameOrder();
                                                gameOrder.setId(orderList.get(i).getId());
                                                gameOrder.setDealStatus((byte) 1);
                                                gameOrder.setWinRecord("三同号通选("+results+")");
                                                gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                                BigDecimal myBalance;
                                                if (orderList.get(i).getSingleAmount().doubleValue() == 2.00) {
                                                    User user = new User();
                                                    user.setUserId(orderList.get(i).getUserId());
                                                    myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                    user.setBalance(myBalance);
                                                    userMapper.addBalanceByPrimaryKey(user);
                                                } else {
                                                    User user = new User();
                                                    user.setUserId(orderList.get(i).getUserId());
                                                    myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(0.1)).multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                    user.setBalance(myBalance);
                                                    userMapper.addBalanceByPrimaryKey(user);
                                                }
                                                gameAwardDeql(orderList.get(i).getUserId(),myBalance);
                                                accountDetailedService.updateAccount((byte) 2,myBalance,"中奖",orderList.get(i).getUserId());
                                                //追号
                                                refundChase(orderList.get(i));
                                                break;
                                            }
                                        }

                                    }

                                    if (!lottery) {
                                        //未中奖
                                        GameOrder gameOrder = new GameOrder();
                                        gameOrder.setId(orderList.get(i).getId());
                                        gameOrder.setDealStatus((byte) 2);
                                        gameOrderMapper.updateByPrimaryKeySelective(gameOrder);

                                    }
                                }
                            } else {
                                //未中奖
                                GameOrder gameOrder = new GameOrder();
                                gameOrder.setId(orderList.get(i).getId());
                                gameOrder.setDealStatus((byte) 2);
                                gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                            }

                        }
                        break;

                    case 4:
                        //二同号复选
                        if (dealStatus == 0) {
                            int value1 = Integer.parseInt(codeNum[0]);
                            int value2 = Integer.parseInt(codeNum[1]);
                            int value3 = Integer.parseInt(codeNum[2]);
                            if (value1 == value2 || value2 == value3) {
                                String gameResult = orderList.get(i).getGameResult();
                                List<String> list = JSON.parseArray(gameResult, String.class);
                                if (list != null && list.size() > 0) {
                                    boolean lottery = false;
                                    for (int j = 0; j < list.size(); j++) {
                                        String results = list.get(j);
                                        String[] resultArray = results.split(",");
                                        if (resultArray != null && resultArray.length == 2) {
                                            int result1 = Integer.parseInt(resultArray[0]);

                                            if (value2 == result1) {
                                                //中奖
                                                lottery = true;
                                                GameOrder gameOrder = new GameOrder();
                                                gameOrder.setId(orderList.get(i).getId());
                                                gameOrder.setDealStatus((byte) 1);
                                                gameOrder.setWinRecord("二同号复选("+results+")");
                                                gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                                BigDecimal myBalance;
                                                if (orderList.get(i).getSingleAmount().doubleValue() == 2.00) {
                                                    User user = new User();
                                                    user.setUserId(orderList.get(i).getUserId());
                                                    myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                    user.setBalance(myBalance);
                                                    userMapper.addBalanceByPrimaryKey(user);
                                                } else {
                                                    User user = new User();
                                                    user.setUserId(orderList.get(i).getUserId());
                                                    myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(0.1)).multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                    user.setBalance(myBalance);
                                                    userMapper.addBalanceByPrimaryKey(user);
                                                }
                                                gameAwardDeql(orderList.get(i).getUserId(),myBalance);
                                                accountDetailedService.updateAccount((byte) 2,myBalance,"中奖",orderList.get(i).getUserId());
                                                //追号
                                                refundChase(orderList.get(i));
                                                break;
                                            }
                                        }
                                    }
                                    if (!lottery) {
                                        //未中奖
                                        GameOrder gameOrder = new GameOrder();
                                        gameOrder.setId(orderList.get(i).getId());
                                        gameOrder.setDealStatus((byte) 2);
                                        gameOrderMapper.updateByPrimaryKeySelective(gameOrder);

                                    }
                                }

                            } else {
                                //未中奖
                                GameOrder gameOrder = new GameOrder();
                                gameOrder.setId(orderList.get(i).getId());
                                gameOrder.setDealStatus((byte) 2);
                                gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                            }
                        }
                        break;

                    case 5:
                        //二同号单选
                        if (dealStatus == 0) {
                            String gameResult = orderList.get(i).getGameResult();
                            List<String> list = JSON.parseArray(gameResult, String.class);
                            if (list != null && list.size() > 0) {
                                boolean lottery = false;
                                for (int j = 0; j < list.size(); j++) {
                                    String[] resultArray = list.get(j).split(",");
                                    if (resultArray != null && resultArray.length == 3) {
                                        List<Integer> integerList = new ArrayList<>();
                                        for (String str : resultArray) {
                                            integerList.add(Integer.valueOf(str));

                                        }
                                        Collections.sort(integerList);
                                        StringBuffer sb = new StringBuffer();
                                        for (int z = 0; z < integerList.size(); z++) {
                                            if (z == 1) {
                                                sb.append("," + integerList.get(z));
                                            } else {
                                                sb.append(integerList.get(z));
                                            }
                                        }

                                        if (openCode.equals(sb.toString())) {
                                            //中奖
                                            lottery = true;
                                            GameOrder gameOrder = new GameOrder();
                                            gameOrder.setId(orderList.get(i).getId());
                                            gameOrder.setDealStatus((byte) 1);
                                            gameOrder.setWinRecord("二同号单选("+list.get(j)+")");
                                            gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                            BigDecimal myBalance;
                                            if (orderList.get(i).getSingleAmount().doubleValue() == 2.00) {
                                                User user = new User();
                                                user.setUserId(orderList.get(i).getUserId());
                                                myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                user.setBalance(myBalance);
                                                userMapper.addBalanceByPrimaryKey(user);
                                            } else {
                                                User user = new User();
                                                user.setUserId(orderList.get(i).getUserId());
                                                myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(0.1)).multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                user.setBalance(myBalance);
                                                userMapper.addBalanceByPrimaryKey(user);
                                            }
                                            gameAwardDeql(orderList.get(i).getUserId(),myBalance);
                                            accountDetailedService.updateAccount((byte) 2,myBalance,"中奖",orderList.get(i).getUserId());
                                            //追号
                                            refundChase(orderList.get(i));
                                            break;
                                        }
                                    }
                                }
                                if (!lottery) {
                                    //未中奖
                                    GameOrder gameOrder = new GameOrder();
                                    gameOrder.setId(orderList.get(i).getId());
                                    gameOrder.setDealStatus((byte) 2);
                                    gameOrderMapper.updateByPrimaryKeySelective(gameOrder);

                                }
                            }
                        }

                        break;
                    case 6:
                        //三不同号
                        if (dealStatus == 0) {
                            String gameResult = orderList.get(i).getGameResult();
                            List<String> list = JSON.parseArray(gameResult, String.class);
                            if (list != null && list.size() > 0) {
                                boolean lottery = false;
                                for (String str : list) {
                                    if (openCode.equals(str)) {
                                        //中奖
                                        lottery = true;
                                        GameOrder gameOrder = new GameOrder();
                                        gameOrder.setId(orderList.get(i).getId());
                                        gameOrder.setDealStatus((byte) 1);
                                        gameOrder.setWinRecord("三不同号("+str+")");
                                        gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                        BigDecimal myBalance;
                                        if (orderList.get(i).getSingleAmount().doubleValue() == 2.00) {
                                            User user = new User();
                                            user.setUserId(orderList.get(i).getUserId());
                                            myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                            user.setBalance(myBalance);
                                            userMapper.addBalanceByPrimaryKey(user);
                                        } else {
                                            User user = new User();
                                            user.setUserId(orderList.get(i).getUserId());
                                            myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(0.1)).multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                            user.setBalance(myBalance);
                                            userMapper.addBalanceByPrimaryKey(user);
                                        }

                                        gameAwardDeql(orderList.get(i).getUserId(),myBalance);
                                        accountDetailedService.updateAccount((byte) 2,myBalance,"中奖",orderList.get(i).getUserId());
                                        //追号
                                        refundChase(orderList.get(i));
                                        break;

                                    }

                                }

                                if(!lottery){
                                    GameOrder gameOrder = new GameOrder();
                                    gameOrder.setId(orderList.get(i).getId());
                                    gameOrder.setDealStatus((byte) 2);
                                    gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                }
                            }
                        }
                        break;
                    case 7:
                        //二不同号
                        if(dealStatus==0){
                            String gameResult = orderList.get(i).getGameResult();
                            List<String> list = JSON.parseArray(gameResult, String.class);
                            if(list!=null&&list.size()>0){
                                boolean lottery = false;
                                for (String str:list) {
                                    String[] resultArray = str.split(",");
                                    if(resultArray!=null&&resultArray.length==2){
                                        String result1 = resultArray[0];
                                        String result2 = resultArray[1];
                                        if(openCode.contains(result1)&&openCode.contains(result2)){
                                            //中奖
                                            lottery = true;
                                            GameOrder gameOrder = new GameOrder();
                                            gameOrder.setId(orderList.get(i).getId());
                                            gameOrder.setDealStatus((byte) 1);
                                            gameOrder.setWinRecord("二不同号("+str+")");
                                            gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                            BigDecimal myBalance;
                                            if (orderList.get(i).getSingleAmount().doubleValue() == 2.00) {
                                                User user = new User();
                                                user.setUserId(orderList.get(i).getUserId());
                                                myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                user.setBalance(myBalance);
                                                userMapper.addBalanceByPrimaryKey(user);
                                            } else {
                                                User user = new User();
                                                user.setUserId(orderList.get(i).getUserId());
                                                myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(0.1)).multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                                user.setBalance(myBalance);
                                                userMapper.addBalanceByPrimaryKey(user);
                                            }
                                            gameAwardDeql(orderList.get(i).getUserId(),myBalance);
                                            accountDetailedService.updateAccount((byte) 2,myBalance,"中奖",orderList.get(i).getUserId());
                                            //追号
                                            refundChase(orderList.get(i));
                                            break;
                                        }
                                    }
                                }
                                if(!lottery){
                                    GameOrder gameOrder = new GameOrder();
                                    gameOrder.setId(orderList.get(i).getId());
                                    gameOrder.setDealStatus((byte) 2);
                                    gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                }
                            }
                        }

                        break;
                    case 8:
                        //三连号通选
                        if(dealStatus==0){
                            String gameResult = orderList.get(i).getGameResult();
                            List<String> list = JSON.parseArray(gameResult, String.class);
                            if(list!=null&&list.size()>0){
                                boolean lottery = false;
                                for (String str: list) {
                                    if(openCode.equals(str)){
                                        //中奖
                                        lottery = true;
                                        GameOrder gameOrder = new GameOrder();
                                        gameOrder.setId(orderList.get(i).getId());
                                        gameOrder.setDealStatus((byte) 1);
                                        gameOrder.setWinRecord("三连号通选("+str+")");
                                        gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                        BigDecimal myBalance;
                                        if (orderList.get(i).getSingleAmount().doubleValue() == 2.00) {
                                            User user = new User();
                                            user.setUserId(orderList.get(i).getUserId());
                                            myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                            user.setBalance(myBalance);
                                            userMapper.addBalanceByPrimaryKey(user);
                                        } else {
                                            User user = new User();
                                            user.setUserId(orderList.get(i).getUserId());
                                            myBalance = orderList.get(i).getWinningAmount().multiply(new BigDecimal(0.1)).multiply(new BigDecimal(orderList.get(i).getMultiple()));
                                            user.setBalance(myBalance);
                                            userMapper.addBalanceByPrimaryKey(user);
                                        }
                                        gameAwardDeql(orderList.get(i).getUserId(),myBalance);
                                        accountDetailedService.updateAccount((byte) 2,myBalance,"中奖",orderList.get(i).getUserId());
                                        //追号
                                        refundChase(orderList.get(i));
                                        break;
                                    }

                                }

                                if(!lottery){
                                    GameOrder gameOrder = new GameOrder();
                                    gameOrder.setId(orderList.get(i).getId());
                                    gameOrder.setDealStatus((byte) 2);
                                    gameOrderMapper.updateByPrimaryKeySelective(gameOrder);
                                }
                            }

                        }
                        break;
                    default:

                        break;
                }

            }
        }
    }

    /**
     * 未读消息数
     * @param userId
     * @return
     */
    @Override
    public long getUnraadNum(Long userId) {
        BjksRecord record1 = bjksRecordMapper.selectCurrentRecord((byte) 1);
        BjksRecord record2 = bjksRecordMapper.selectCurrentRecord((byte) 2);
        BjksRecord record3 = bjksRecordMapper.selectCurrentRecord((byte) 3);
        String num1 = null;
        String num2 = null;
        String num3 = null;
        if(record1!=null){
            num1 = record1.getNum();
        }
        if(record2!=null){
            num2 = record2.getNum();
        }
        if(record3!=null){
            num3 = record3.getNum();
        }
        long count = gameOrderMapper.selectUnReadNum(userId, (byte) 0,num1,num2,num3);
        return count;
    }

    /**
     * 我的信箱
     * @param userId
     * @return
     */
    @Override
    public List<GameOrder> getMailBox(Long userId) {
        BjksRecord record1 = bjksRecordMapper.selectCurrentRecord((byte) 1);
        BjksRecord record2 = bjksRecordMapper.selectCurrentRecord((byte) 2);
        BjksRecord record3 = bjksRecordMapper.selectCurrentRecord((byte) 3);
        GameOrderExample gameOrderExample = new GameOrderExample();
        String num1 = null;
        String num2 = null;
        String num3 = null;
        if(record1!=null){
            num1 = record1.getNum();
            GameOrderExample.Criteria criteria = gameOrderExample.createCriteria();
            criteria.andRecordIdLessThan(num1);
            criteria.andUserIdEqualTo(userId);
        }
        if(record2!=null){
            num2 = record2.getNum();
            GameOrderExample.Criteria criteria2 = gameOrderExample.or();
            criteria2.andRecordIdLessThan(num2);
            criteria2.andUserIdEqualTo(userId);
        }
        if(record3!=null){
            num3 = record3.getNum();
            GameOrderExample.Criteria criteria3 = gameOrderExample.or();
            criteria3.andRecordIdLessThan(num3);
            criteria3.andUserIdEqualTo(userId);
        }

        if(gameOrderExample.getOredCriteria().size()==0){
            GameOrderExample.Criteria criteria = gameOrderExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
        }

        //查询最近20期数据
        List<GameOrder> orders = gameOrderMapper.getLastTwentyOrders(userId,num1,num2,num3);
        List<String> recordIds = new ArrayList<>();
        List<GameOrder> myOrders = new ArrayList<>();
        for (int i=0;i<orders.size();i++){
            if(recordIds.contains(orders.get(i).getRecordId())){
                if(orders.get(i).getWinRecord()!=null){
                    String record = myOrders.get(recordIds.indexOf(orders.get(i).getRecordId())).getWinRecord();
                    if(record==null){
                        record = orders.get(i).getWinRecord();
                    }else{
                        record = record+orders.get(i).getWinRecord();
                    }
                    myOrders.get(recordIds.indexOf(orders.get(i).getRecordId())).setWinRecord(record);
                }
            }else{
                recordIds.add(orders.get(i).getRecordId());
                myOrders.add(orders.get(i));
            }
        }

        List<GameOrder> msgOrders  = gameOrderMapper.selectByExample(gameOrderExample);
        if(msgOrders!=null&&msgOrders.size()>0){
            for (int i = 0;i<msgOrders.size();i++){
                if(msgOrders.get(i).getReadStatus()==0){
                    GameOrder gameOrderStatus = new GameOrder();
                    gameOrderStatus.setId(msgOrders.get(i).getId());
                    gameOrderStatus.setReadStatus((byte) 1);
                    gameOrderMapper.updateByPrimaryKeySelective(gameOrderStatus);
                }
            }
        }


        return myOrders;
    }

    /**
     * 追号
     *
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int chaseNumber(Long userId, Long gameid,Integer chaseCount, Short multiple, Integer period, Integer beiNum, BigDecimal money, Byte isStop,Byte gameCategory,Byte gameType,String gameResult,Byte buy_num,BigDecimal single_amount,BigDecimal winningAmount) {
        BjksRecord record = bjksRecordMapper.selectByPrimaryKey(gameid);
        Date endTime = record.getEndTime();
        long currentTime = System.currentTimeMillis();
        User userInfo = userMapper.selectByPrimaryKey(userId);
        double balance = userInfo.getBalance().doubleValue();
        if(money.doubleValue()>balance){
            //余额不足
            return 3;
        }

        if(endTime.getTime()<currentTime){

            return 0;
        }
        long startNum = 0;
        if ((endTime.getTime() - currentTime) < 4 * 60 * 1000) {
            //本期不可追
            startNum = Long.parseLong(record.getNum())+1;


        }else{
            //本期可追
            startNum = Long.parseLong(record.getNum());
        }

        GameOrderExample gameOrderExample = new GameOrderExample();
        GameOrderExample.Criteria criteria = gameOrderExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andRecordIdGreaterThanOrEqualTo(String.valueOf(startNum));
        criteria.andGameResultEqualTo(gameResult);
        criteria.andGameTypeEqualTo(gameType);
        criteria.andSingleAmountEqualTo(single_amount);
        criteria.andIsChaseEqualTo((byte) 1);
        List<GameOrder> myOrders = gameOrderMapper.selectByExample(gameOrderExample);

        if(myOrders!=null&&myOrders.size()>0){
            return Integer.parseInt(myOrders.get(myOrders.size()-1).getRecordId());
        }


        userInfo.setBalance(userInfo.getBalance().subtract(money));
        userMapper.updateByPrimaryKeySelective(userInfo);

        accountDetailedService.updateAccount((byte) 3,money,"追号下注",userId);

        for (int i = 0;i<chaseCount;i++){
            GameOrder gameOrder = new GameOrder();
            gameOrder.setGameCategory(gameCategory);
            gameOrder.setUserId(userId);
            gameOrder.setGameType(gameType);
            gameOrder.setGameResult(gameResult);
            gameOrder.setRecordId(String.valueOf(startNum+i));
            gameOrder.setBuyNum(buy_num);
            double myMultiple = multiple*Math.pow(beiNum,i/period);
            gameOrder.setIsstop(isStop);
            gameOrder.setMultiple((short) myMultiple);
            gameOrder.setSingleAmount(single_amount);
            BigDecimal myBetting = new BigDecimal(myMultiple*buy_num*single_amount.doubleValue());
            gameOrder.setBettingAmount(myBetting);
            gameOrder.setWinningAmount(winningAmount);
            gameOrder.setCreateTime(new Date());
            gameOrder.setIsChase((byte) 1);
            gameOrderMapper.insertSelective(gameOrder);

        }

        return 1;
    }

    @Override
    public void refundChase(GameOrder gameOrder) {
        if(gameOrder.getIsChase()==1&&gameOrder.getIsstop()==1){
            GameOrderExample gameOrderExample = new GameOrderExample();
            GameOrderExample.Criteria criteria = gameOrderExample.createCriteria();
            criteria.andRecordIdGreaterThan(gameOrder.getRecordId());
            criteria.andIsChaseEqualTo((byte) 1);
            criteria.andIsstopEqualTo((byte) 1);
            criteria.andGameResultEqualTo(gameOrder.getGameResult());
            criteria.andDealStatusEqualTo((byte) 0);
            criteria.andUserIdEqualTo(gameOrder.getUserId());
            List<GameOrder> list = gameOrderMapper.selectByExample(gameOrderExample);
            if(list!=null&&list.size()>0){
                BigDecimal count = new BigDecimal(0.00);
                for (GameOrder order: list) {
                    BigDecimal bigDecimal = order.getBettingAmount();
                    count = count.add(bigDecimal);
                    GameOrder order1 = new GameOrder();
                    order1.setId(order.getId());
                    order1.setDealStatus((byte) 3);
                    gameOrderMapper.updateByPrimaryKeySelective(order1);

                }

                User myuser = userMapper.selectByPrimaryKey(gameOrder.getUserId());
                BigDecimal balance =myuser.getBalance();
                balance = balance.add(count);
                User user = new User();
                user.setUserId(myuser.getUserId());
                user.setBalance(balance);
                userMapper.updateByPrimaryKeySelective(user);

                accountDetailedService.updateAccount((byte) 4,count,"退款",myuser.getUserId());
            }
        }

    }

    @Override
    public List<BjksRecord> getRecordByDate(Byte gameGategory, String date) {
        return bjksRecordMapper.getRecordByDate(gameGategory, date);

    }

    @Override
    public void gameAwardDeql(long userId,BigDecimal balance){
        User user = userMapper.selectByPrimaryKey(userId); // 中奖人
        BigDecimal allCount = balance.multiply(new BigDecimal(awardPercentage));
        Map<Long,BigDecimal> map = new HashMap<>();
        if(user.getGrade()==1){
            log.info("中奖用户："+userId+"一级用户不加奖");
            map.put(userId,allCount);

        }else{
            List<Long> userIds = new ArrayList<>();
            List<BigDecimal> antis = new ArrayList<>();

            log.info("中奖用户："+userId+"加奖金额："+allCount.doubleValue());
            OpenAccount account = openAccountMapper.selectByAccountName(user.getUserName());
            userIds.add(account.getUserId());
            antis.add(account.getAntiWater());
            User user1 = userMapper.selectByPrimaryKey(account.getUserId());//1级加奖用户
            if(user1.getGrade()!=1){
                OpenAccount account1 = openAccountMapper.selectByAccountName(user1.getUserName());
                userIds.add(account1.getUserId());
                antis.add(account1.getAntiWater());
                User user2 = userMapper.selectByPrimaryKey(account1.getUserId());//2级加奖用户
                if(user2.getGrade()!=1){
                    OpenAccount account2 = openAccountMapper.selectByAccountName(user2.getUserName());
                    userIds.add(account2.getUserId());
                    antis.add(account2.getAntiWater());

                }
            }
            if(userIds.size()==1){
                Long id1 = userIds.get(0);
                BigDecimal one = allCount.multiply(antis.get(0));
                map.put(userId,allCount.subtract(one));
                map.put(id1,one);
            }else if(userIds.size()==2){
                Long id1 = userIds.get(0);
                BigDecimal one = allCount.multiply(antis.get(0));
                map.put(userId,allCount.subtract(one));
                Long id2 = userIds.get(1);
                BigDecimal two = one.multiply(antis.get(1));
                map.put(id1,one.subtract(two));
                map.put(id2,two);
            }else if(userIds.size()==3){
                Long id1 = userIds.get(0);
                BigDecimal one = allCount.multiply(antis.get(0));
                map.put(userId,allCount.subtract(one));
                Long id2 = userIds.get(1);
                BigDecimal two = one.multiply(antis.get(1));
                map.put(id1,one.subtract(two));
                Long id3 = userIds.get(2);
                BigDecimal three = two.multiply(antis.get(2));
                map.put(id2,two.subtract(three));
                map.put(id3,three);

            }

        }

        for (Map.Entry<Long,BigDecimal> en: map.entrySet()) {
            Long key = en.getKey();
            BigDecimal myBalance = en.getValue();
            log.info("uid:"+key+"value:"+myBalance.doubleValue());
            User lastUser = new User();
            lastUser.setUserId(key);
            lastUser.setBalance(myBalance);
            userMapper.addBalanceByPrimaryKey(lastUser);
            AccountDetailed detailed = new AccountDetailed();
            detailed.setType((byte) 5);
            detailed.setUserId(key);
            detailed.setMoney(myBalance);
            detailed.setCreateTime(new Date());
            detailed.setIncomeMessage("加奖");
            accountDetailedMapper.insertSelective(detailed);

        }

    }


}
